<template>
<view class="container">
    <view class="tab">
      <view v-for="(item, index) in tab" :key="index" :style="'width:' + (100/(tab.length)) + '%;'" :class="(showTabIndex == index ? 'activeTab':'noneUse')" :data-id="index" @tap="bindTab">{{item.name}}</view>        
    </view>

    <swiper class="Tab_page" :current="showTabIndex" :style="'height: ' + (sysHeight-50) + 'px;'" @change="changeIndex"> 
      <swiper-item v-for="(tab, index) in tab" :key="index">
          <scroll-view :style="'height: ' + (sysHeight-40) + 'px;'" class="tab_page_list" scroll-y upper-threshold="-30" lower-threshold="10" :data-index="index" @scrolltoupper="scrollTopToReflesh" @scrolltolower="scrollBottomToLoadMore">
            <view class="tab_page_list_container" style="background: #eee;">
                <block v-if="!tab.List">  
                    <view class="noneList">没有相关订单</view>
                </block>
                <block v-else> 
                    <view class="cartContainer" v-for="(list, i) in tab.List" :key="i">
                      <view class="promotionNameItem" v-if="list.promotionName">
                        <view class="promotionNameLine"></view>
                        <view class="promotionName" :style="'background:' + setting.platformSetting.defaultColor"><text>{{list.promotionName}}</text></view>
                      </view>
                      <view class="cartShopName"> 
                        <view class="storageName" v-if="list.storageName"><text>{{list.storageName}}</text></view>
                        <!-- <text class='font1'>客户名：{{list.buyerName}}</text> -->
                        <view style="display:flex; align-items:center;"> 
                        <view>
                            <view class="orderType" v-if="list.orderType==0">
                              <image class="orderTypeIcon" src="https://image1.sansancloud.com/sansancloud/2018_9/4/16/40/15_518.jpg?x-oss-process=style/preview_120"></image>
                            </view>
                            <view class="orderType" v-else-if="list.orderType==10">
                               <image class="orderTypeIcon" src="https://image1.sansancloud.com/sansancloud/2018_9/4/16/40/15_511.jpg?x-oss-process=style/preview_120"></image>
                            </view>
                            <view class="orderType" v-else-if="list.orderType==11">
                               <image class="orderTypeIcon" src="https://image1.sansancloud.com/sansancloud/2018_9/4/16/40/15_535.jpg?x-oss-process=style/preview_120"></image>
                            </view>
                            <view class="orderType" v-else-if="list.orderType==4">
                              <image class="orderTypeIcon" src="https://image1.sansancloud.com/sansancloud/2018_9/4/16/40/15_530.jpg?x-oss-process=style/preview_120"></image>
                            </view>
                            <view class="orderType" v-else-if="list.orderType==7">
                               <image class="orderTypeIcon" src="https://image1.sansancloud.com/sansancloud/2018_9/4/16/40/15_466.jpg?x-oss-process=style/preview_120"></image>
                            </view>
                          </view>
                          <text>订单号:{{list.orderNo}}</text>
                           <!-- <image wx:if="{{list.buyerHeadimg}}" src='{{list.buyerHeadimg}}' mode='aspectFill'
                          style='width:2em; height:2em; border:1px solid #ccc;border-radius:50%;'>
                          </image>
                          <text class='font1' style='margin-left:10rpx; max-width:5em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;'>{{list.buyerNickName}}</text> -->
                          <!-- <text class="marginleft vity_tag" wx:if='{{list.promotionName}}'>{{list.promotionName}}</text> -->
                        </view>
                        <block> 
                          <text class :style="'color:' + setting.platformSetting.defaultColor">{{list.orderStatusStr}}</text>
                        </block>
                        <!-- <block wx:elif='{{list.easyStatusStr == "完成"}}'> 
                          <text class='' style='color:{{setting.platformSetting.defaultColor}}'>交易成功</text>
                        </block>
                        <block wx:elif='{{list.easyStatusStr == "待评价"}}'> 
                          <text class='' style='color:{{setting.platformSetting.defaultColor}}'>待完成</text>
                        </block>
                        <block wx:else>
                          <text class='' style='color:{{setting.platformSetting.defaultColor}}'>{{list.easyStatusStr}}</text>
                        </block> -->
                      </view>

                      <view class="cartItems" :data-orderno="list.orderNo">
                      <!--  bindtap='toOrderDetail' -->
                        <view class="itemCheckbox">
                          <image mode="aspectFill" :src="list.itemIcon + '?x-oss-process=style/preview'" v-if="list.itemIcon"></image>
                          <!-- <view class='promotionName' wx:if='{{list.promotionName}}'><text>{{list.promotionName}}</text></view> -->
                        </view>
                        <view class="item_infomation">
                          <view class="item_infomation_name font1">{{list.itemName}}</view>

                          <view class="item_infomation_name2" v-if="!!list.measureCartesianId">{{list.measures}}</view>
                          <view class="item_infomation_nums"> 
                            <text class="flexCenter">x {{list.itemCount}}</text>
                          </view>
                          <view class="item_infomation_money">
                            <view>供货价：￥<text class="fontPrice">{{list.supplyPrice}}</text></view>
                            <text v-if="list.itemCode">商品编码：【{{list.itemCode}}】</text>
                          </view>
                        </view>
                      </view>

                      <view class="butn_container">
                          
                          <!-- <text>订单金额￥{{list.goodsAmount - list.youhuiAmount}}</text> -->
                          <text :style="'color:' + setting.platformSetting.defaultColor">（预估收入￥{{list.supplyPrice}}）</text>
                      </view>
                      <!-- 订单类型不同，按钮不一样 -->
                      <view class="butn_container2">
                          <view class="butn_group" v-if="list.orderStatus==1&&list.payStatus==1">
                            <text :data-orderNo="list.orderNo" class="butn_item" :data-index="index" @tap="confirmMendianOrder">确认订单</text>
                            <text :data-orderNo="list.orderNo" class="butn_item" :data-index="index" @tap="rejectMendianOrder">拒绝订单</text>
                          </view>
                          <text v-else>{{list.addTime}}</text>
                      </view>

                    </view>
                     <view v-if="tab.listEnd" class="dixian"> 我是有底线的 ~</view> 
                </block>
            </view>
          </scroll-view>
      </swiper-item>
    </swiper>
</view>
</template>

<script>

export default {
  data() {
    return {
      orderList: [],
      reflesh: false,
      showTabIndex: 0,
      sysWidth: 320,
      sysHeight: 568,
      tab: [
        {
          name: '全部',
          getUrl: 'order_list_0.html',
          params: {
            easyStatusName: "全部订单",
            easyStatus: '0',
            page: 1
          },
          List: []
        },
        {
          name: '待付款',
          getUrl: 'order_list_2.html',
          params: {
            easyStatusName: "待付款",
            easyStatus: '2',
            page: 1
          },
          List: []
        },
        {
          name: '待发货',
          getUrl: 'order_list_3.html',
          params: {
            easyStatusName: "待发货",
            easyStatus: '3',
            page: 1
          },
          List: []
        },
        {
          name: '待收货',
          getUrl: 'order_list_4.html',
          params: {
            easyStatusName: "待收货",
            easyStatus: '4',
            page: 1
          },
          List: []
        },
        {
          name: '已完成',
          getUrl: 'order_list_6.html',
          params: {
            easyStatusName: "已完成",
            easyStatus: '6',
            page: 1
          },
          List: []
        },
      ],
      opt: {},
      setting: "",
      loginUser: ""
    };
  },

  components: {},
  props: {},
  onLoad: function (options) {
    this.opt = options;
    console.log(options);
    this.dellOpt(options);
  },
  onReady: function () {
    this.setData({
      setting: getApp().globalData.setting,
      loginUser: getApp().globalData.loginUser,
      sysWidth: getApp().globalData.sysWidth,
      sysHeight: getApp().globalData.sysHeight
    });
  },
  methods: {
    confirmMendianOrder: function (e) {
      console.log("=====confirmMendianOrder=====", e);
      var orderNo = e.currentTarget.dataset.orderno;
      var index = e.currentTarget.dataset.index;
      let tab = this.tab;
      let focusTab = tab[index];
      var that = this;
      wx.showModal({
        title: '提示',
        content: '确认订单',
        success: function (res) {
          if (res.confirm) {
            let param_post = {};
            param_post.orderItemId = orderNo;
            var customIndex = getApp().globalData.AddClientUrl("/confirm_mendian_order_item.html", param_post, 'post');
            wx.request({
              url: customIndex.url,
              data: customIndex.params,
              header: getApp().globalData.headerPost,
              method: 'POST',
              success: function (res) {
                if (res.data.errcode == '0') {
                  console.log(res.data);
                  wx.showToast({
                    title: '确认订单成功',
                    icon: 'success',
                    duration: 1000
                  });
                  setTimeout(function () {
                    focusTab.params.page = 1;
                    that.getOrderList(focusTab, index, 1);
                  }, 1000);
                } else {
                  wx.showToast({
                    title: res.data.errMsg,
                    image: '/wxcomponents/images/icons/tip.png',
                    duration: 1000
                  });
                }
              },
              fail: function (res) {
                getApp().globalData.loadFail();
              }
            });
          } else if (res.cancel) {}
        }
      });
    },
    rejectMendianOrder: function (e) {
      console.log("=====rejectMendianOrder=====", e);
      var orderNo = e.currentTarget.dataset.orderno;
      var index = e.currentTarget.dataset.index;
      let tab = this.tab;
      let focusTab = tab[index];
      var that = this;
      wx.showModal({
        title: '提示',
        content: '拒绝订单',
        success: function (res) {
          if (res.confirm) {
            let param_post = {};
            param_post.orderItemId = orderNo;
            var customIndex = getApp().globalData.AddClientUrl("/reject_mendian_order_item.html", param_post, 'post');
            wx.request({
              url: customIndex.url,
              data: customIndex.params,
              header: getApp().globalData.headerPost,
              method: 'POST',
              success: function (res) {
                if (res.data.errcode == '0') {
                  console.log(res.data);
                  wx.showToast({
                    title: '拒绝订单成功',
                    icon: 'success',
                    duration: 1000
                  });
                  setTimeout(function () {
                    focusTab.params.page = 1;
                    that.getOrderList(focusTab, index, 1);
                  }, 1000);
                } else {
                  wx.showToast({
                    title: res.data.errMsg,
                    image: '/wxcomponents/images/icons/tip.png',
                    duration: 1000
                  });
                }
              },
              fail: function (res) {
                getApp().globalData.loadFail();
              }
            });
          } else if (res.cancel) {}
        }
      });
    },
    toOrderDetail: function (e) {
      let orderNo = e.currentTarget.dataset.orderno;
      wx.navigateTo({
        url: '/pages/order_detail/index?orderNo=' + orderNo
      });
    },

    /* 点击tab */
    bindTab: function (e) {
      var index = e.currentTarget.dataset.id;

      if (this.showTabIndex == index) {
        return;
      }

      this.setData({
        showTabIndex: index
      });
    },

    /* 滑动事件 */
    changeIndex: function (e) {
      var index = e.detail.current;
      let tab = this.tab;
      let focusTab = tab[index];

      if (!focusTab.List || focusTab.List.length == 0) {
        this.getOrderList(focusTab, index);
      }

      this.setData({
        showTabIndex: index
      });
    },
    //得到他的利润
    distributeProfit: function (result) {
      for (let i = 0; i < result.length; i++) {
        result[i].distributeProfitResult = 0; // for (let j = 0; j < result[i].orderItems.length; j++ ){
        //   let getMoneyItem = result[i].orderItems[j].distributeProfit * result[i].orderItems[j].itemCount
        //   result[i].distributeProfitResult += getMoneyItem
        // }
        // result[i].distributeProfitResult = (result[i].distributeProfitResult * (app.setting.platformSetting.mendianDistributeProfit)/100).toFixed(2)
      }

      return result;
    },

    /* 获取数据 */
    getOrderList: function (focusTab, index, fresh) {
      let params = focusTab.params;
      let tab = this.tab;
      var customIndex = getApp().globalData.AddClientUrl("/get_mendian_order_items_admin_mendian_json.html", params, 'post');
      var that = this; // wx.showLoading({
      //   title: 'loading'
      // })

      getApp().globalData.showToastLoading('loading', true);
      wx.request({
        url: customIndex.url,
        data: customIndex.params,
        header: getApp().globalData.headerPost,
        method: 'POST',
        success: function (res) {
          console.log('-----------orderList--------');
          console.log(res.data);

          if (res.data.errcode == '0') {
            focusTab.params.pageSize = res.data.relateObj.pageSize;
            focusTab.params.curPage = res.data.relateObj.curPage;
            focusTab.params.totalSize = res.data.relateObj.totalSize;
            let result = that.distributeProfit(res.data.relateObj.result);

            if (fresh) {
              focusTab.List = [];
            }

            if (!result || result.length == 0) {
              focusTab.List = null;
            } else {
              focusTab.List = focusTab.List.concat(result);
            }

            tab[index] = focusTab;
            that.setData({
              tab: tab
            });
          } else {
            console.log('error');
          }

          wx.hideLoading();
        },
        fail: function (res) {
          wx.hideLoading();
          getApp().globalData.loadFail();
        }
      });
    },

    /* 加载更多 */
    scrollBottomToLoadMore: function (e) {
      let that = this;
      console.log(this.loading);

      if (this.loading) {
        return;
      }

      this.loading = true;
      let index = e.currentTarget.dataset.index;
      let tab = this.tab;
      let focusTab = tab[index];

      if (focusTab.params.totalSize > focusTab.params.curPage * focusTab.params.pageSize) {
        console.log('hasMore');
        ++focusTab.params.page;
        this.getOrderList(focusTab, index);
      }

      setTimeout(function () {
        that.loading = false;
      }, 2000);
    },

    /* 第一次加载 */
    dellOpt: function (options) {
      if (this.tab.length == 0) {
        return;
      }

      let easyStatus = options.easyStatus;

      if (!easyStatus) {
        easyStatus = 0;
      }

      let tab = this.tab;
      let index = 0;

      for (let i = 0; i < tab.length; i++) {
        if (tab[i].params.easyStatus == easyStatus) {
          index = i;
        }
      }

      this.getOrderList(tab[index], index);
      this.setData({
        showTabIndex: index
      });
    },

    /* 订单详细 */
    lookMore: function (e) {
      var orderNo = e.currentTarget.dataset.orderno;
      console.log(orderNo);
      this.setData({
        reflesh: true
      });
      wx.navigateTo({
        url: '/pages/order_detail/index?orderNo=' + orderNo
      });
    },
    setData: function (obj) {
      let that = this;
      let keys = [];
      let val, data;
      Object.keys(obj).forEach(function (key) {
        keys = key.split('.');
        val = obj[key];
        data = that.$data;
        keys.forEach(function (key2, index) {
          if (index + 1 == keys.length) {
            that.$set(data, key2, val);
          } else {
            if (!data[key2]) {
              that.$set(data, key2, {});
            }
          }

          data = data[key2];
        });
      });
    }
  }
};
</script>
<style>
@import "./index.css";
</style>